package com.yonyou.pmclouds.team.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.rpc.RpcContext;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.PMControllerConst;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.util.ChineseStringUtils;
import com.yonyou.pmclouds.enterprise.entity.EnterpriseInfo;
import com.yonyou.pmclouds.outter.enterprise.EnterpriseInfoQuery;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import com.yonyou.pmclouds.team.entity.TeamEnterpriseRefVO;
import com.yonyou.pmclouds.team.entity.TeamEnterpriseVO;
import com.yonyou.pmclouds.team.entity.TeamMemberVO;
import com.yonyou.pmclouds.team.rmiitf.TeamEnterpriseQuery;
import com.yonyou.pmclouds.team.rmiitf.TeamMemberMaintain;
import com.yonyou.pmclouds.team.rmiitf.TeamMemberQuery;
import com.yonyou.pmclouds.user.entity.UserInfo;
import com.yonyou.pmclouds.user.entity.UserSearchResultVO;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.*;

@Controller
@RequestMapping("/team")
public class TeamMemberController {
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private TeamMemberQuery query;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private TeamMemberMaintain maintain;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private TeamEnterpriseQuery enterpriseQuery;

    @Autowired
    private UserInfoQuery userInfoQuery;
    @Autowired
    private EnterpriseInfoQuery enterpriseInfoQuery;

    @GetMapping("/members")
    @ResponseBody
    public TeamMemberVO[] getMembers(@RequestParam("projectid") String projectid) throws BusinessException {
        final TeamMemberVO[] teamMembers = query.queryByProject(projectid);
        userInfoAdd(teamMembers);
        //  企业信息添加
        enterpriseInfoQuery.tranEntInfoField(teamMembers, new String[]{TeamMemberVO.PK_ENTERPRISE}, new String[]{TeamMemberVO.ENTERPRISE_NAME});
        if (ArrayUtils.isEmpty(teamMembers)) {
            return teamMembers;
        }
        Arrays.sort(teamMembers, new Comparator<TeamMemberVO>() {
            @Override
            public int compare(TeamMemberVO o1, TeamMemberVO o2) {
                if (o1 == o2) {
                    return 0;
                }
                if (o1 == null) {
                    return 1;
                }
                if (o2 == null) {
                    return -1;
                }
                if (!o1.getUserRole().equals(o2.getUserRole())) {
                    return o1.getUserRole().compareTo(o2.getUserRole());
                }
                int com = ChineseStringUtils.compareInDict(o1.getEnterpriseName(), o2.getEnterpriseName());
                if (com != 0) {
                    return com;
                }
                return ChineseStringUtils.compareInDict(o1.getUserName(), o2.getUserName());

            }
        });
        return teamMembers;
    }

    @Deprecated
    @PostMapping("/addMembers")
    @ResponseBody
    public TeamMemberVO[] addMembers(@RequestBody AddMemberViewVO viewVO)
            throws BusinessException {
        if (StringUtils.isEmpty(viewVO.projectid) || ArrayUtils.isEmpty(viewVO.members)) {
            return new TeamMemberVO[0];
        }
        Map<String, String> attach = RpcContext.getContext().getAttachments();
        attach = new HashMap<>(attach);
        TeamMemberVO[] filledMems = fillEnterpriseOnInsert(viewVO);
        // FIXME dubbo多次调用会导致attach失掉，目前无法使用代理来处理掉
        RpcContext.getContext().setAttachments(attach);
        String[] memberPks = maintain.addMembersToProject(viewVO.projectid, filledMems);
        // 查询一下增加的项目团队
        TeamMemberVO[] members = query.queryById(memberPks);
        userInfoAdd(members);
        // 企业信息添加
        enterpriseInfoQuery.tranEntInfoField(members, new String[]{TeamMemberVO.PK_ENTERPRISE}, new String[]{TeamMemberVO.ENTERPRISE_NAME});
        return members;
    }

    private TeamMemberVO[] fillEnterpriseOnInsert(@RequestBody AddMemberViewVO viewVO) throws BusinessException {
        // 查询参与企业
        // 这里存在风险点，可能存在数据不一致，不过member的保存有校验，所以问题不大
        TeamEnterpriseVO[] ents = enterpriseQuery.queryByProject(viewVO.projectid);
        Set<String> availableEnts = new HashSet<>(ents.length);
        for (TeamEnterpriseVO ent : ents) {
            availableEnts.add(ent.getPkEnterprise());
        }
        // 查询用户企业
        Map<String, EnterpriseInfo[]> userEnterpriseMap = enterpriseInfoQuery.getEnterprisesOfUsers(viewVO.members);
        if (userEnterpriseMap == null || userEnterpriseMap.size() == 0) {
            throw new BusinessException("所选用户未隶属于任何企业！");
        }
        TeamMemberVO[] memberVOs = new TeamMemberVO[viewVO.members.length];
        for (int i = 0; i < memberVOs.length; i++) {
            memberVOs[i] = new TeamMemberVO();
            memberVOs[i].setPkUser(viewVO.members[i]);
            //  构造企业，用户企业与参与企业取交集
            String onwEnt = null;
            EnterpriseInfo[] userEnts = userEnterpriseMap.get(viewVO.members[i]);
            if (ArrayUtils.isEmpty(userEnts)) {
                BusinessException ex = new BusinessException();
                ex.addInfo("userNotInEnt", memberVOs[i].getPkUser());
                throw ex;
            }
            for (EnterpriseInfo userEnt : userEnts) {
                if (availableEnts.contains(userEnt.getId())) {
                    onwEnt = userEnt.getId();
                    break;
                }
            }
            memberVOs[i].setPkEnterprise(onwEnt);
        }
        return memberVOs;
    }

    @PostMapping("/remove")
    @ResponseBody
    public String removeMember(@RequestBody TeamMemberVO memberVO)
            throws BusinessException {
        maintain.removeFromTeam(memberVO.getPkTeamMember(), memberVO.getChangeFlag());
        return memberVO.getPkTeamMember();
    }

    @RequestMapping("/search")
    @ResponseBody
    public UserSearchResultVO.ContentVO searchUser(@RequestBody QueryUserVO queryUserVO) throws BusinessException {
        int iPageNum = StringUtils.isEmpty(queryUserVO.getPageNum())?1:Integer.valueOf(queryUserVO.getPageNum());
        int iPageSize = StringUtils.isEmpty(queryUserVO.getPageSize())?Integer.valueOf(PMControllerConst.DEFAULT_PAGE_SIZE): Integer.valueOf(queryUserVO.getPageSize());

        String[] excludeUser = new String[]{};
        if(ArrayUtils.isNotEmpty(queryUserVO.getExcludeUser()))
            excludeUser = queryUserVO.getExcludeUser();

        return userInfoQuery.searchUsers(queryUserVO.getKeyword(), queryUserVO.getEnterid(), iPageNum, iPageSize, excludeUser);

    }

    @RequestMapping("/constructionUnits")
    @ResponseBody
    public TeamEnterpriseRefVO[] getConstructionUnit(@RequestParam("projectid") String projectid) throws BusinessException {
        TeamEnterpriseRefVO[] result = enterpriseQuery.queryConstructionUnitInProject(projectid);
//        enterpriseInfoQuery.tranEntInfoField(result, new String[]{TeamEnterpriseVO.PK_ENTERPRISE}, new String[]{TeamEnterpriseVO.ENTERPRISE_NAME});
        return result;
    }

    /**
     * 监理单位
     */
    @RequestMapping("/supervisionUnits")
    @ResponseBody
    public TeamEnterpriseRefVO[] getSupervisionUnit(@RequestParam("projectid") String projectid) throws BusinessException {
        TeamEnterpriseRefVO[] result = enterpriseQuery.querySupervisionUnitInProject(projectid);
//        enterpriseInfoQuery.tranEntInfoField(result, new String[]{TeamEnterpriseVO.PK_ENTERPRISE}, new String[]{TeamEnterpriseVO.ENTERPRISE_NAME});
        return result;
    }
    private void userInfoAdd(TeamMemberVO[] memberVOs) {
        if (ArrayUtils.isEmpty(memberVOs)) {
            return;
        }
        Map<String, UserInfo> users = userInfoQuery.extractUserInfoFromBeans(memberVOs, new String[]{TeamMemberVO.PK_USER});
        for (TeamMemberVO member : memberVOs) {
            UserInfo user = users.get(member.getPkUser());
            if (user == null) {
                continue;
            }
            member.setUserName(user.getUserName());
            member.setEmail(user.getUserEmail());
            member.setPhoneNo(user.getUserMobile());
        }
    }

    @Getter
    @Setter
    private static class AddMemberViewVO {
        private String[] members;
        private String projectid;
    }


}
@Getter
@Setter
class QueryUserVO implements Serializable{
    String keyword;
    String enterid;
    String pageNum;
    String pageSize;
    String[] excludeUser;

}
